import axios from 'axios';

// 创建用户服务实例（8090端口）
const userHttp = axios.create({
  baseURL: 'http://localhost:8090',
  timeout: 10000,
  paramsSerializer: params => {
    return Object.entries(params)
      .map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`)
      .join('&');
  }
});

// 创建景点服务实例（8070端口）
const spotHttp = axios.create({
  baseURL: 'http://localhost:8070',
  timeout: 10000,
  paramsSerializer: params => {
    return Object.entries(params)
      .map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`)
      .join('&');
  }
});

// 请求拦截器配置
const setupInterceptors = (instance) => {
  instance.interceptors.request.use(
    config => {
      const token = localStorage.getItem('token');
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    },
    error => {
      return Promise.reject(error);
    }
  );

  instance.interceptors.response.use(
    response => {
      return response;
    },
    error => {
      if (error.response) {
        return Promise.reject(error.response.data);
      }
      return Promise.reject(error);
    }
  );
};

// 为两个实例设置拦截器
setupInterceptors(userHttp);
setupInterceptors(spotHttp);

export { userHttp, spotHttp };